<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :destroyOnClose="true"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入项目名称"
                v-decorator="['projectName', validatorRules.projectName]"
                :disabled="disableSubmit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                showSearch
                placeholder="请选择客户"
                :filterOption="filterOption"
                v-decorator="['customerId', validatorRules.customerId]"
                :disabled="customerId ? true : disableSubmit"
                @change="handleCustomerChange"
              >
                <a-select-option v-for="customer in customerList" :key="customer.id" :value="customer.id">
                  {{ customer.customerName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入联系人"
                v-decorator="['contactPerson', validatorRules.contactPerson]"
                :disabled="disableSubmit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入联系电话"
                v-decorator="['contactPhone', validatorRules.contactPhone]"
                :disabled="disableSubmit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                v-decorator="['status', validatorRules.status]"
                placeholder="请选择项目状态"
                :disabled="disableSubmit"
              >
                <a-select-option :value="0">未开始</a-select-option>
                <a-select-option :value="1">进行中</a-select-option>
                <a-select-option :value="2">已完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                style="width: 100%"
                placeholder="请输入项目金额"
                v-decorator="['projectAmount']"
                :disabled="disableSubmit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker style="width: 100%" v-decorator="['startDate']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker style="width: 100%" v-decorator="['endDate']" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="省市区" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
              <j-area-linkage
                type="cascader"
                v-decorator="['area', validatorRules.area]"
                @change="areaChange"
                :disabled="disableSubmit"
                ref="areaLinkage"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="详细地址" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
              <a-textarea placeholder="请输入详细地址" v-decorator="['address']" :rows="2" :disabled="disableSubmit" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="项目描述" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18 }">
              <a-textarea
                placeholder="请输入项目描述"
                v-decorator="['description']"
                :rows="4"
                :disabled="disableSubmit"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { projectAdd, projectEdit } from '@/api/crm'
  import { getAction } from '@/api/manage'
  import JAreaLinkage from '@/components/jeecg/JAreaLinkage'
import Area from '@/components/_util/Area'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import { validateMobile } from '@/utils/validate'

  export default {
  name: 'ProjectModal',
    components: {
    JAreaLinkage,
    },
    data() {
      return {
      title: '操作',
        width: 800,
        visible: false,
        model: {},
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          projectName: { 
          rules: [{ required: true, message: '请输入项目名称!' }],
          },
          customerId: { 
          rules: [{ required: true, message: '请选择客户!' }],
          },
          contactPerson: { 
          rules: [{ required: true, message: '请输入联系人!' }],
          },
          contactPhone: { 
          rules: [{ required: true, message: '请输入联系电话!' }, { validator: this.validatePhone }],
          },
          status: { 
          rules: [{ required: true, message: '请选择项目状态!' }],
          },
          area: {
          rules: [{ required: true, message: '请选择省市区!' }],
        },
        },
        disableSubmit: false,
        customerList: [],
        customerId: '',
        customerName: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        provinceName: '',
        cityName: '',
      areaName: '',
      }
    },
    methods: {
    add(customerData) {
      // 基础项目数据
      let projectData = { status: 0 }

      // 如果传入了客户数据，则合并到项目数据中
      if (customerData) {
        projectData = Object.assign(projectData, customerData)
      }

      this.edit(projectData)
      },
      edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      
      // 确保status是数字类型
      if(record.status !== undefined && record.status !== null) {
        this.model.status = Number(record.status)
      }
      
      this.visible = true

      console.log('编辑工程数据:', record)
        
        // 处理省市区数据
        if (record.provinceCode) {
        // 保存区域代码和名称
        this.provinceCode = record.provinceCode
        this.cityCode = record.cityCode || ''
        this.areaCode = record.areaCode || ''
        this.provinceName = record.provinceName || ''
        this.cityName = record.cityName || ''
        this.areaName = record.areaName || ''

        // 构建区域数组数据
        const areaArray = [this.provinceCode]
        if (this.cityCode) {
          areaArray.push(this.cityCode)
          if (this.areaCode) {
            areaArray.push(this.areaCode)
          }
        }

        if (areaArray.length > 0) {
          this.model.area = areaArray
        }

        console.log('设置省市区数据:', {
          provinceCode: this.provinceCode,
          cityCode: this.cityCode,
          areaCode: this.areaCode,
          area数组: areaArray,
        })

        // 如果名称不存在，尝试从代码反推名称
        if (!this.provinceName || !this.cityName || !this.areaCode) {
          this.$nextTick(() => {
            this.inferAreaNamesFromCodes()
          })
        }
        }
        
        // 处理日期
        if (record.startDate) {
        this.model.startDate = moment(record.startDate)
        }
        if (record.endDate) {
        this.model.endDate = moment(record.endDate)
        }
        
        // 处理客户ID
        if (record.customerId) {
        this.customerId = record.customerId
        this.customerName = record.customerName
      } else {
        this.customerId = ''
        this.customerName = ''
      }

      // 先加载客户列表
      this.loadCustomerList()

      // 然后设置表单值
        this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'projectName',
            'contactPerson',
            'contactPhone',
            'status',
            'projectAmount',
            'startDate',
            'endDate',
            'address',
            'description',
            'area'
          )
        )

        // 表单设置完成后记录日志
        setTimeout(() => {
          this.logAreaData()
        }, 100)
      })
      },
      close() {
      this.$emit('close')
      this.visible = false
      },
      handleOk() {
      const that = this
        if (this.disableSubmit) {
        this.close()
        return
        }
        
        this.form.validateFields((err, values) => {
          if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)

          console.log('表单数据处理前:', formData)
            
            // 处理省市区数据
          if (values.area) {
            // 如果area是数组形式，表示级联选择器的值
            if (Array.isArray(values.area)) {
              formData.provinceCode = values.area[0] || ''
              formData.cityCode = values.area.length > 1 ? values.area[1] : ''
              formData.areaCode = values.area.length > 2 ? values.area[2] : ''
              
              // 尝试获取对应的名称
              try {
                if (formData.provinceCode && this.$Jpcaa && this.$Jpcaa['86']) {
                  formData.provinceName = this.$Jpcaa['86'][formData.provinceCode] || ''
                }
                
                if (formData.provinceCode && formData.cityCode && this.$Jpcaa && this.$Jpcaa[formData.provinceCode]) {
                  formData.cityName = this.$Jpcaa[formData.provinceCode][formData.cityCode] || ''
                }
                
                if (formData.provinceCode && formData.cityCode && formData.areaCode && 
                    this.$Jpcaa && this.$Jpcaa[formData.provinceCode] && 
                    this.$Jpcaa[formData.provinceCode][formData.cityCode]) {
                  formData.areaName = this.$Jpcaa[formData.provinceCode][formData.cityCode][formData.areaCode] || ''
                }
              } catch (e) {
                console.error('获取省市区名称失败:', e)
              }
            } 
            // 如果没有设置，确保所有省市区信息都为空
            else if (!values.area) {
              formData.provinceCode = ''
              formData.provinceName = ''
              formData.cityCode = ''
              formData.cityName = ''
              formData.areaCode = ''
              formData.areaName = ''
            }
          }

          // 如果使用了组件内部的provinceCode等变量，确保它们优先被使用
          if (this.provinceCode) {
            formData.provinceCode = this.provinceCode
            formData.provinceName = this.provinceName || ''
          }
          if (this.cityCode) {
            formData.cityCode = this.cityCode
            formData.cityName = this.cityName || ''
          }
          if (this.areaCode) {
            formData.areaCode = this.areaCode
            formData.areaName = this.areaName || ''
            }
            
            // 处理日期
            if (values.startDate) {
            formData.startDate = values.startDate.format('YYYY-MM-DD')
            }
            if (values.endDate) {
            formData.endDate = values.endDate.format('YYYY-MM-DD')
            }
            
            // 处理客户ID
            if (this.customerId) {
            formData.customerId = this.customerId
            formData.customerName = this.customerName
            }
            
          console.log('表单数据处理后，准备提交:', formData)

          let obj
            if (!this.model.id) {
            obj = projectAdd(formData)
            } else {
            obj = projectEdit(formData)
            }
            
          obj
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
      },
      handleCancel() {
      this.close()
      },
      validatePhone(rule, value, callback) {
        if (value && !validateMobile(value)) {
        callback('请输入正确的手机号码!')
        } else {
        callback()
        }
      },
      areaChange(values, labels) {
      //当前values是区编号字符串，通过区编号反推城、市编号 以及获得对应的名称
      console.log('地区选择变更 - 原始值:', values, labels)

      if (!values) {
        // 清空选择
        this.provinceCode = ''
        this.provinceName = ''
        this.cityCode = ''
        this.cityName = ''
        this.areaCode = ''
        this.areaName = ''
        return
      }

      // 判断是否选择了区级信息
      const isAreaSelected = typeof values === 'string' && values.length > 0

      if (isAreaSelected) {
        // 获取区级编码
        this.areaCode = values

        // 根据区编号反推城市和省编号
        if (this.$Jpcaa) {
          try {
            // 从Area数据中查找区域信息
            const area = new Area(this.$Jpcaa)
            if (area && area.pca) {
              // 获取区级数据
              const areaData = area.pca.find((item) => item.id === this.areaCode && item.index === 3)

              if (areaData) {
                // 获取区名称
                this.areaName = areaData.text

                // 获取城市编码
                this.cityCode = areaData.pid

                // 获取城市数据
                const cityData = area.pca.find((item) => item.id === this.cityCode && item.index === 2)
                if (cityData) {
                  // 获取城市名称
                  this.cityName = cityData.text

                  // 获取省级编码
                  this.provinceCode = cityData.pid

                  // 获取省级数据
                  const provinceData = area.pca.find((item) => item.id === this.provinceCode && item.index === 1)
                  if (provinceData) {
                    // 获取省名称
                    this.provinceName = provinceData.text
                  }
                }
              } else {
                // 如果找不到区级数据，尝试使用反推方法
                const codes = area.getRealCode(this.areaCode)
                if (codes && codes.length > 0) {
                  if (codes.length >= 1) this.provinceCode = codes[0]
                  if (codes.length >= 2) this.cityCode = codes[1]
                  if (codes.length >= 3) this.areaCode = codes[2]

                  // 获取名称
                  this.inferAreaNamesFromCodes()
                }
              }
            }
          } catch (error) {
            console.error('反推区域编码失败:', error)
            // 如果反推失败，尝试从labels获取
            if (labels) {
              this.areaName = labels
            }
          }
        }

        // 如果区域名称已获取但省市信息未获取，使用常规方法获取
        if (this.areaName && (!this.provinceName || !this.cityName)) {
          this.getAreaNamesByCodes()
        }

        // 更新表单的area字段值为完整的省市区编码数组
        if (this.provinceCode) {
          const areaArray = [this.provinceCode]
          if (this.cityCode) {
            areaArray.push(this.cityCode)
            if (this.areaCode) {
              areaArray.push(this.areaCode)
            }
          }
          this.form.setFieldsValue({ area: areaArray })
        }

        console.log('地区选择变更 - 处理后:', {
          provinceCode: this.provinceCode,
          provinceName: this.provinceName,
          cityCode: this.cityCode,
          cityName: this.cityName,
          areaCode: this.areaCode,
          areaName: this.areaName,
        })
      } else {
        // 如果values是数组形式，说明使用了级联选择器
        if (Array.isArray(values) && values.length > 0) {
          this.provinceCode = values[0] || ''
          this.cityCode = values.length > 1 ? values[1] : ''
          this.areaCode = values.length > 2 ? values[2] : ''

          // 初始化省市区名称为空
          this.provinceName = ''
          this.cityName = ''
          this.areaName = ''

          // 如果labels是有效数组，从labels获取名称
          if (Array.isArray(labels) && labels.length > 0) {
            this.provinceName = labels[0] || ''
            this.cityName = labels.length > 1 ? labels[1] : ''
            this.areaName = labels.length > 2 ? labels[2] : ''
          }

          // 尝试获取完整的省市区名称
          this.inferAreaNamesFromCodes()
        }
      }
    },

    // 从区级代码反推完整的省市区名称
    inferAreaNamesFromCodes() {
      if (!this.$Jpcaa) {
        console.warn('地区数据未加载，无法反推省市区名称')
        return false
      }

      try {
        let namesFound = false

        // 首先尝试获取区名称
        if (this.provinceCode && this.cityCode && this.areaCode) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityData = provinceData[this.cityCode]
              if (cityData && typeof cityData === 'object') {
                const areaName = cityData[this.areaCode]
                if (typeof areaName === 'string') {
                  this.areaName = areaName
                  namesFound = true

                  // 当成功获取区名称后，确保也获取省市名称
                  const provinceName = this.$Jpcaa['86'][this.provinceCode]
                  if (provinceName && typeof provinceName === 'string') {
                    this.provinceName = provinceName
                  }

                  const cityName = provinceData[this.cityCode]
                  if (cityName && typeof cityName === 'string') {
                    this.cityName = cityName
                  }
                }
              }
            }
          } catch (e) {
            console.warn('反推区名称失败:', e)
          }
        }

        // 如果无法获取区名称，尝试获取市名称
        if (!namesFound && this.provinceCode && this.cityCode) {
          try {
            const provinceData = this.$Jpcaa[this.provinceCode]
            if (provinceData && typeof provinceData === 'object') {
              const cityName = provinceData[this.cityCode]
              if (cityName && typeof cityName === 'string') {
                this.cityName = cityName
                namesFound = true

                // 当成功获取市名称后，确保也获取省名称
                const provinceName = this.$Jpcaa['86'][this.provinceCode]
                if (provinceName && typeof provinceName === 'string') {
                  this.provinceName = provinceName
                }
              }
            }
          } catch (e) {
            console.warn('反推市名称失败:', e)
          }
        }

        // 如果无法获取市名称，尝试获取省名称
        if (!namesFound && this.provinceCode) {
          try {
            const provinceName = this.$Jpcaa['86'][this.provinceCode]
            if (provinceName && typeof provinceName === 'string') {
              this.provinceName = provinceName
              namesFound = true
            }
          } catch (e) {
            console.warn('反推省名称失败:', e)
          }
        }

        return namesFound
      } catch (error) {
        console.error('反推省市区名称失败:', error)
        return false
      }
    },

    // 设置区域数据
    setAreaData(provinceCode, cityCode, areaCode) {
      if (!provinceCode) return

      try {
        // 构建区域编码数组
        const areaArray = []
        areaArray.push(provinceCode)
        if (cityCode) areaArray.push(cityCode)
        if (areaCode) areaArray.push(areaCode)

        console.log('手动设置区域编码:', areaArray)

        // 设置表单字段值
        this.form.setFieldsValue({ area: areaArray })

        // 保存区域编码
        this.provinceCode = provinceCode
        this.cityCode = cityCode || ''
        this.areaCode = areaCode || ''

        // 初始化区域名称为空
        this.provinceName = ''
        this.cityName = ''
        this.areaName = ''

        // 使用反推方法获取省市区名称
        this.inferAreaNamesFromCodes()

        console.log('区域名称已设置:', {
          provinceName: this.provinceName,
          cityName: this.cityName,
          areaName: this.areaName,
        })
      } catch (error) {
        console.error('设置省市区数据失败:', error)
      }
    },

    // 打印当前的省市区数据，用于调试
    logAreaData() {
      console.log('当前省市区数据:', {
        表单area值: this.form.getFieldValue('area'),
        provinceCode: this.provinceCode,
        provinceName: this.provinceName,
        cityCode: this.cityCode,
        cityName: this.cityName,
        areaCode: this.areaCode,
        areaName: this.areaName,
      })
    },
    
    // 根据区域编码获取区域名称
    getAreaNamesByCodes() {
      if (!this.$Jpcaa) {
        console.warn('地区数据未加载，无法获取省市区名称')
        return false
      }
      
      try {
        // 使用内置的反推方法获取省市区名称
        return this.inferAreaNamesFromCodes()
      } catch (error) {
        console.error('根据区域编码获取区域名称失败:', error)
        return false
      }
    },
    
      loadCustomerList() {
      getAction('/crm/customer/listAll').then((res) => {
          if (res.success) {
          this.customerList = res.result || []

          // 如果已有客户ID，确保在下一个事件循环中设置表单值
          if (this.customerId) {
            this.$nextTick(() => {
              this.form.setFieldsValue({
                customerId: this.customerId,
              })
            })
          }
        }
      })
      },
      handleCustomerChange(value) {
      const customer = this.customerList.find((item) => item.id === value)
        if (customer) {
        this.customerId = customer.id
        this.customerName = customer.customerName
          
          // 自动填充联系人信息
          this.form.setFieldsValue({
            contactPerson: customer.contactPerson,
          contactPhone: customer.contactPhone,
        })
          
          // 自动填充地址信息
          if (customer.provinceCode) {
          const area = [customer.provinceCode, customer.cityCode, customer.areaCode]
          this.provinceCode = customer.provinceCode
          this.cityCode = customer.cityCode
          this.areaCode = customer.areaCode
          this.provinceName = customer.provinceName
          this.cityName = customer.cityName
          this.areaName = customer.areaName
            this.form.setFieldsValue({
              area: area,
            address: customer.address,
          })
          }
        }
      },
      filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    show(record) {
      this.form.resetFields();
      
      // 处理customerId参数
      if (record && record.customerId) {
        this.customerId = record.customerId;
      } else {
        this.customerId = '';
      }
      
      if (record && record.id) {
        // 编辑模式
        this.edit(record);
      } else {
        // 新增模式
        this.add();
        
        // 如果传入了客户ID，自动设置客户
        if (this.customerId) {
          this.form.setFieldsValue({
            customerId: this.customerId
          });
        }
      }
    },
  },
  created() {
    // 在组件创建时初始化
    console.log('项目表单组件创建')
  },
  mounted() {
    // 确保pcaa数据加载完成
    if (!this.$Jpcaa) {
      console.warn('地区数据未加载，可能会影响省市区选择功能')
    } else {
      console.log('地区数据已加载')

      // 如果是编辑模式且有省市区数据，进行处理
      if (this.model && this.model.provinceCode) {
        this.$nextTick(() => {
          // 确保数据已经加载完成后再设置
          this.setAreaData(this.model.provinceCode, this.model.cityCode, this.model.areaCode)
        })
      }
    }
  },
  }
</script>

<style scoped>
</style> 